<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CustomerAppletsUserWechat extends Model
{
    protected $table      = "customerapplets_user_wechats";
    protected $primaryKey = "id";

    /**
     * 根据openid查询信息是否存在
     * @param $store_id
     * @param $open_id
     * @param string $js_code
     * @param string $session_key
     * @return array|bool|int
     */
    public function getUserOpenidInfo($store_id,$open_id,$js_code = "" , $session_key = ""){
        if(!isset($store_id) || empty($store_id)){
            return false;
        }
        if(!isset($open_id) || empty($open_id)) {
            return false;
        }

        $date = date("Y-m-d H:i:s",time());
        //先判断该openid用户有没有再该门店登陆过
        $userInfo = DB::table("customerapplets_users")->where(['store_id' => $store_id,'third_party_id' => $open_id])->first();

        if(!empty($userInfo)){
            //说明登录过,再判断customerapplets_user_wechats表中有没有存这位用户的微信信息
            $userWeChatResult = $this->where(['store_id' => $store_id,'wechat_openid' => $open_id])->first();
            if(!empty($userWeChatResult)){
                //说明已经存在
                if(!empty($session_key)){
                    $updateResult = $this->where(['store_id' => $store_id,'wechat_openid' => $open_id])->update([
                        'wechat_session_key' => $session_key,
                        'updated_at'         => $date
                    ]);
                }
            }else{
                //说明不存在
                $user_weChat_info['user_id']        = $userInfo->id;
                $user_weChat_info['store_id']       = $store_id;
                $user_weChat_info['wechat_open_id'] = $open_id;
                if(!empty($session_key)){
                    $user_weChat_info['wechat_session_key'] = $session_key;
                }
                $user_weChat_info['created_at'] = $date;
                $user_weChat_info['updated_at'] = $date;
                $user_weChat_result = $this->insert($user_weChat_info);
                if(!$user_weChat_result){
                    return ["status" => "202","message" => "用户微信数据插入失败"];
                }
            }
            return $userInfo->id;
        }else{
            //说明未登陆过
            //开启事务
            DB::beginTransaction();
            try{
                $user_id = DB::table("customerapplets_users")->insertGetId([
                    'store_id'           => $store_id,
                    'code'               => $js_code,
                    'user_source'        => 1,
                    'third_party_id'     => $open_id,
                    'created_at'         => $date,
                    'updated_at'         => $date
                ]);

                if($user_id){

                    $user_weChat_info['user_id']        = $user_id;
                    $user_weChat_info['store_id']       = $store_id;
                    $user_weChat_info['wechat_openid']  = $open_id;
                    if(!empty($session_key)){
                        $user_weChat_info['wechat_session_key'] = $session_key;
                    }
                    $user_weChat_info['created_at'] = $date;
                    $user_weChat_info['updated_at'] = $date;
                    $user_weChat_result = $this->insert($user_weChat_info);
                    if(!$user_weChat_result){
                        return ["status" => "202","message" => "用户微信数据插入失败"];
                    }
                }else{
                    return ["status" => "202","message" => "用户数据插入失败"];
                }

                DB::commit();
                return $user_id;
            }catch (\Exception $e) {
                DB::rollBack();
                return ["status" => "202","message" => $e->getMessage()];
            }
        }
    }

    /**
     * 更新用户的微信基本信息
     * @param $user_id
     * @param $store_id
     * @param $weChat_data_info
     * @return array|bool
     */
    public function updateUserWeChatInfo($user_id,$store_id,$weChat_data_info){
        if(!$user_id || !$store_id){
            return false;
        }

        $userInfo = $this->where(['user_id' => $user_id,'store_id' => $store_id])->first();

        if(empty($userInfo)){
            return ["status" => 202,"message" => "用户信息不存在，请授权"];
        }else{
            //转义微信用户名中的表情
            $tmpStr = json_encode($weChat_data_info['nickName']); //暴露出unicode
            $content = preg_replace_callback("#(\\\ue[0-9a-f]{3})#i", function($a) {
                return addslashes($a[1]);
            }, $tmpStr);

            $result = $this->where(['user_id' => $user_id,'store_id' => $store_id])->update([
                'wechat_gender'         => $weChat_data_info['gender'],
                'wechat_avatar'         => $weChat_data_info['avatarUrl'],
                'wechat_username'       => $content,
                'wechat_user_country'   => $weChat_data_info['country'],
                'wechat_user_province'  => $weChat_data_info['province'],
                'wechat_user_city'      => $weChat_data_info['city'],
                'updated_at'            => date("Y-m-d H:i:s",time())
            ]);
            if($result){
                return ["status" => 200,"message" => "更新成功"];
            }else{
                return ["status" => 202,"message" => "更新失败"];
            }
        }
    }

    /**
     * 查找用户微信信息
     * @param $user_id
     * @param $store_id
     * @return bool
     */
    public function getUserInfo($user_id,$store_id){
        if(!isset($user_id) || empty($user_id)){
            return false;
        }
        if(!isset($store_id) || empty($store_id)){
            return false;
        }

        $result = $this->where(['user_id' => $user_id,'store_id' => $store_id])->first();

        if(is_null(json_decode($result->wechat_username))){
            $result->wechat_username = "";
        }else{
            $result->wechat_username = json_decode($result->wechat_username,true);
        }

        if(!empty($result)){
            return $result;
        }else{
            return false;
        }
    }

}
